package top.revery.datasource.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.web.bind.annotation.RestController;
import top.revery.api.api.adv.IAdvApi;
import top.revery.api.config.UserPageData;
import top.revery.api.entity.other.BaseAdv;
import top.revery.datasource.dto.AdvDto;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.Map;

/**
 * @author denghao
 * @title
 * @package
 * @date 2019/12/21 10:00
 */
@RestController
public class AdvServiceController implements IAdvApi {
    @Autowired
    private AdvDto advDto;
    @Override
    public BaseAdv save(BaseAdv baseAdv) throws Exception {
        try {
            
           return advDto.save(baseAdv);
            
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
        
    }

    @Override
    public UserPageData getList(int pageNum, int pageSize, Map map) {

        Page<BaseAdv> pageList = findPage(pageNum, pageSize, map);
        UserPageData userPageData = new UserPageData();
        userPageData.list = pageList.getContent();
        userPageData.rows = pageList.getTotalElements();
        return userPageData;
    }

    private Page<BaseAdv> findPage(int pageNum, int pageSize, Map map) {


        Specification<BaseAdv> specification = new Specification<BaseAdv>() {
            @Override
            public Predicate toPredicate(Root<BaseAdv> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                Predicate predicate = cb.conjunction();
                //id
                if (map.get("id") != null && !"".equals(map.get("id"))) {
                    predicate.getExpressions().add(cb.equal(root.get("id"), map.get("id")));
                }
                //根据名字模糊查询
                if (map.get("name") != null && !"".equals(map.get("name"))) {
                    predicate.getExpressions().add(cb.like(root.get("name"), (String) map.get("name")));
                }
                return predicate;
            }
        };
        PageRequest pageRequest = PageRequest.of(pageNum - 1, pageSize);
        return advDto.findAll(specification, pageRequest);
    }

}
